<!-- Copyright (c) Microsoft Corporation.
     Licensed under the MIT License. -->

<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dev Proxy - Microsoft Graph JavaScript SDK Sample</title>
    <link rel="stylesheet" href="https://unpkg.com/@n8d/htwoo-core@1.2.5/dist/css/htwoo.min.css">
    <link rel="stylesheet"
        href="https://static2.sharepointonline.com/files/fabric/office-ui-fabric-core/11.0.0/css/fabric.min.css" />
    <link rel="stylesheet" href="./style/theme.css">
    <script src="https://alcdn.msauth.net/browser/2.28.3/js/msal-browser.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/@microsoft/microsoft-graph-client/lib/graph-js-sdk.js"></script>
    <script
        src="https://cdn.jsdelivr.net/npm/@microsoft/microsoft-graph-client/lib/graph-client-msalBrowserAuthProvider.js"></script>
    <script src="env.js"></script>
    <script src="https://unpkg.com/@n8d/htwoo-core@1.2.5/dist/js/umd/htwoo.min.js"></script>
    <style>
        #content {
            display: flex;
            flex-flow: row wrap;
            justify-content: space-around;
            row-gap: 2em;
            column-gap: 2em;
            padding: 2em;
            align-items: stretch;
        }

    </style>
</head>

<body class="ms-Fabric" dir="ltr">
    <div id="content"></div>
    <div id="auth"></div>
    <script>
        ((appId, msal, MSGraphAuthCodeMSALBrowserAuthProvider) => {
            const msalClient = new msal.PublicClientApplication({
                auth: {
                    clientId: appId
                }
            });

            function render() {
                document.querySelector('div#content').innerHTML = "";
                document.querySelector('#auth').innerHTML = "";

                const accounts = msalClient.getAllAccounts();

                if (accounts.length === 0) {
                    const element = `<div class="hoo-splashscr">
                                        <div class="hoo-splashscr-content">
                                            <article class="hoo-splashcard">
                                            <header class="hoo-splashcard-header" role="presentation">
                                                <img src="img/devproxy.png" alt="Dev Proxy" class="hoo-splashcard-img">
                                            </header>
                                            <h1 class="hoo-splashcard-title">
                                                Dev Proxy
                                            </h1>
                                            <p class="hoo-splashcard-desc">
                                                Microsoft Graph JavaScript SDK Sample
                                            </p>
                                            <footer class="hoo-splashcard-footer">
                                                <button id="login" class="hoo-button-primary">
                                                    <span class="hoo-button-label">Login</span>
                                                </button>
                                                <button id="back" class="hoo-button">
                                                    <span class="hoo-button-label">Back</span>
                                                </button>
                                            </article>
                                        </div>
                                    </div>`;

                    document.querySelector('#auth').innerHTML = element;

                    document.querySelector('button#login').addEventListener('click', login);
                    document.querySelector('button#back').addEventListener('click', (e) => { e.preventDefault(); window.location.href = "index.html"; });
                }
                else {
                    document.querySelector('#auth').innerHTML = `<div style="display:flex;column-gap:2em;padding:2em;">
                                                                    <button id="logout" class="hoo-button">
                                                                        <span class="hoo-button-label">Logout</span>
                                                                    </button>
                                                                    <button id="back" class="hoo-button">
                                                                        <span class="hoo-button-label">Back</span>
                                                                    </button>
                                                                </div>`;
                    document.querySelector('button#logout').addEventListener('click', logout);
                    document.querySelector('button#back').addEventListener('click', (e) => { e.preventDefault(); window.location.href = "index.html"; });

                    const graphClient = getGraphClient(accounts[0]);
                    callGraph(graphClient);
                }
            }

            function login(e) {
                e.preventDefault();
                msalClient
                    .loginPopup()
                    .then(response => render());
            }

            function logout(e) {
                e.preventDefault();

                msalClient
                    .logoutPopup()
                    .then(response => render());
            }

            function getGraphClient(account) {
                const authProvider = new MSGraphAuthCodeMSALBrowserAuthProvider.AuthCodeMSALBrowserAuthenticationProvider(msalClient, {
                    account,
                    scopes: [
                        'https://graph.microsoft.com/User.Read.All',
                        'https://graph.microsoft.com/Presence.Read.All'
                    ],
                    interactionType: msal.InteractionType.Popup,
                });

                return MicrosoftGraph.Client.initWithMiddleware({ authProvider });
            }

            function callGraph(graphClient) {
                graphClient.api('/users').get()
                    .then((users) => {
                        const usersWithPresence =
                            users.value.map(
                                profile =>
                                    graphClient.api(`/users/${profile.id}/presence`).get()
                                        .then(presence => ({ profile, presence }))
                            );
                        return Promise.all(usersWithPresence)
                    })
                    .then((usersWithPresence) => {
                        const usersWithPresenceAndPhoto =
                            usersWithPresence.map(
                                ({ profile, presence }) =>
                                    graphClient.api(`/users/${profile.id}/photo/$value`).get()
                                        .then(photo => ({ profile, presence, photo }))
                                // .catch(e => ({ profile, presence, photo: null }))
                            );
                        return Promise.all(usersWithPresenceAndPhoto);
                    })
                    .then((usersWithPresenceAndPhoto) =>
                        usersWithPresenceAndPhoto.map((user) => {
                            const element = `<div class="hoo-persona-72">
                                                <div class="hoo-avatar-pres">
                                                    <div class="hoo-avatar">
                                                        <img src="${user.photo ? getImageUrl(user.photo) : null}" alt="${user.profile.displayName}" class="hoo-avatar-img" loading="lazy">
                                                    </div>
                                                    <div class="hoo-presence ${getHooClassFromAvailability(user.presence.availability)}" title="${user.presence.availability}"></div>
                                                </div>
                                                <div class="hoo-persona-data">
                                                    <div class="hoo-persona-name">${user.profile.displayName}</div>
                                                    <div class="hoo-persona-function">${user.profile.jobTitle ? user.profile.jobTitle : 'Chief Executive Officer'}</span></div>
                                                    <div class="hoo-persona-statustext"><span>${user.presence.activity}</span></div>
                                                    <div class="hoo-persona-available"><span>${user.presence.availability}</span></div>
                                                </div>
                                            </div>`;
                            document.querySelector('div#content').innerHTML += element;
                        }))
                // .catch(e => console.log(e))
            }

            function getImageUrl(data) {
                const url = window.URL || window.webkitURL;
                return url.createObjectURL(data);
            }

            function getHooClassFromAvailability(status) {
                switch (status) {
                    case 'Available':
                    case 'AvailableIdle':
                        return 'is-online';
                    case 'Away':
                    case 'BeRightBack':
                    case 'PresenceIdle':
                        return 'is-away';
                    case 'Busy':
                    case 'BusyIdle':
                    case 'DoNotDisturb':
                        return 'is-dnd';
                    case 'Offline':
                    case 'PresenceUnknown':
                        return 'is-invisible';
                    default:
                        return 'is-invisible';
                }
            }

            render();
        })(appId, msal, MSGraphAuthCodeMSALBrowserAuthProvider)

    </script>
</body>

</html>
